var map, vectors, graphic;

function export_vectors() {
    var x = new OpenLayers.Format.XML();
    var content = x.write(vectors.renderer.rendererRoot);
    $("vectors").value = content;
    $("vectors").style.display = "block";
    $("vectorlink").href = "data:image/svg+xml," + escape(content);
    $("vectorlink").style.display="block";
}

function view_svg() {
    var x = new OpenLayers.Format.XML();
    var content = x.write(vectors.renderer.rendererRoot);
    location.href = "data:image/svg+xml," + escape(content);
}

function download_svg() {
    var x = new OpenLayers.Format.XML();
    var content = x.write(vectors.renderer.rendererRoot);
    $("vectorlink").href = "data:application/octet-stream;filename='test.svg'," + escape(content);
    //$("vectorlink").href = "data:application/octet-stream," + escape(content);
}
        
function clear_buffer() {
    vectors.destroyFeatures();
}

function show_svg() {
    $("svg-output").value = SVG.write(
        vectors.features,
        graphic.size.w,
        graphic.size.h
        );
}  

function getFeaturesExtent (features) {
    var maxExtent = null;
    if (features && (features.length > 0)){
        var maxExtent = features[0].geometry.getBounds();
        for(var i=0; i < features.length; i++){
            maxExtent.extend(features[i].geometry.getBounds());
        }
    }
   return maxExtent;
};

function deserialize() {
            var element = document.getElementById('text');
            var wkt_reader = new OpenLayers.Format.WKT;
            var features = wkt_reader.read(element.value);
            var bounds;
            if(features) {
                if(features.constructor != Array) {
                    features = [features];
                }
                for(var i=0; i<features.length; ++i) {
                    if (!bounds) {
                        bounds = features[i].geometry.getBounds();
                    } else {
                        bounds.extend(features[i].geometry.getBounds());
                    }

                }
                vectors.addFeatures(features);
                //map.zoomToExtent(bounds);
                var max_bounds = getVectorsExtent();
                map.zoomToExtent(max_bounds);
                var plural = (features.length > 1) ? 's' : '';
                element.value = features.length + ' feature' + plural + ' added'
            } else {
                element.value = 'Bad input ' + type;
            }
        }
        
function getVectorsExtent () {
    var mExtent = null;
    if (map.layers && (map.layers.length >0)){
        for(var n=0; n < map.layers.length; n++){
            features = map.layers[n].features
                if (features && (features.length > 0)){
        var mExtent = features[0].geometry.getBounds();
        for(var i=0; i < features.length; i++){
            mExtent.extend(features[i].geometry.getBounds());
        }
    }
}
}
        
   return mExtent;
};

function getGeomClass(geometry) {
    var klass = geometry.CLASS_NAME.split(".")[2];
    return klass
    }

function getGeomClass2(feature) {
    var klass = feature.geometry.CLASS_NAME;
    return klass
    }

function getDataTypes (features) {
    if (features && (features.length > 0)){
        var types = '';
        for(var i=0; i < features.length; i++){
            types += getGeomClass(features[i].geometry);

            if (features[i].geometry.CLASS_NAME == "OpenLayers.Geometry.Collection" ) {
                for (var n=0; n < features[i].geometry.components.length; n++) {
                    if (n == 0) {types += " (";}
                    types += getGeomClass(features[i].geometry.components[n]);
                    if (n != features[i].geometry.components.length -1) {
                         types +=  ", ";
                        } else {types +=  ")";}
                    }
            
                if (i != features.length -1 && (features.length >1)){types += " && "}
            }            
        }
    }
return types;
};

       
function modWKT (event) {
      feature = event.feature
      getWKT(feature)
      }
      
function getWKT (feature) {
      var wkt = null;
      var selectedF = null;     
      if (vectors.selectedFeatures.length == 1) {
          if (vectors.selectedFeatures[0].geometry.CLASS_NAME == "OpenLayers.Geometry.Collection" ) {
                wkt = vectors.selectedFeatures[0].geometry.components;
                $("insert").innerHTML = "Select ST_GeomCollFromText('GEOMETRYCOLLECTION(" + wkt + ")',4326);"
    
          } 
          else {
                wkt = vectors.selectedFeatures[0].geometry;
                $("insert").innerHTML = "Select ST_GeomFromEWKT('SRID=4326;" + wkt + "');"
                $("unioned").innerHTML = ''
     }
     $("dothis").innerHTML = "Select a second feature to view a sample Intersect Query"
     } 
     else {
       // multiple features are selected
         if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Collection") {
                 var selectedF = vectors.selectedFeatures;
                 var wkt_list = []
                 for(var feat in selectedF) {
                     selectedF[feat].feature_id = feat;
                     wkt_list[feat] =   "Select ST_GeomCollFromText('GEOMETRYCOLLECTION(" +selectedF[feat].geometry.components + ")',4326)"
                 }
                //$("dothis").innerHTML = "Intersections between Geometrycollections are not supported"
                $("insert").innerHTML = "Intersections between Geometrycollections are not supported"
                $("unioned").innerHTML = "Unions between Geometrycollections are not supported"
    
          } else {
                 var selectedF = vectors.selectedFeatures;
                 var wkt_list = []
                 for(var feat in selectedF) {
                     selectedF[feat].feature_id = feat;
                     wkt_list[feat] = "ST_GeomFromEWKT('SRID=4326;" + selectedF[feat].geometry + "')";
                 }
                 $("insert").innerHTML = "Select " + $('function').value + "(("+ wkt_list[0] + "),(" + wkt_list[1] + "));"                     
           if (document.getElementById("union").checked){
                 var selectedF = vectors.selectedFeatures;
                 var wkt_list = []
                 for(var feat in selectedF) {
                     selectedF[feat].feature_id = feat;
                     wkt_list[feat] = "ST_GeomFromEWKT('SRID=4326;" + selectedF[feat].geometry + "')";
                 }
                 $("unioned").innerHTML = "Select ST_AsText(ST_Union(("+ wkt_list[0] + "),(" + wkt_list[1] + ")));" 
              
              }
     
     
     }
     $("dothis").innerHTML = "Deselect features by clicking them a second time..."
     }
      if (vectors.selectedFeatures.length < 1) {
          $("insert").innerHTML = "No Features Selected..."
          $("unioned").innerHTML = "No Features Selected..."
          $("dothis").innerHTML = "Thanks!"
          }
      }       


function getGeomStyle(){
    
     // create the layer styleMap by giving the default style a context
    var context = {
        getFill: function(feature) {
          if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Collection" ) {
              return "orange"
              }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon" ) {
              return "green"
              }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiPolygon" ) {
              return "yellow"
              }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiPoint" ) {
              return "darkred"
              }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point" ) {
              return "red"
              }
        },
        getStroke: function(feature) {
            if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Collection" ) {
                return "darkblue"
                }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon" ) {
                return "purple"
                }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiPolygon" ) {
              return "purple"
              }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiPoint" ) {
              return "darkgreen"
              }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point" ) {
                return "darkgreen"
                }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" ) {
              return "blue"
              }
             else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiLineString" ) {
              return "darkblue"
              }
        },
        getStrokeWidth: function(feature) {
            if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Collection" ) {
                return 1
                }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Polygon" ) {
                return 1.5
                }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiPolygon" ) {
              return 1.5
              }
          else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiPoint" ) {
              return 1.5
              }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point" ) {
                return .5
                }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.LineString" ) {
              return 3
              }
            else if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.MultiLineString" ) {
              return 3
              }
        }
    };
    
    var template = {
        strokeColor: "${getStroke}", 
        fillColor: "${getFill}",
        strokeWidth: "${getStrokeWidth}",
        pointRadius: 5, 
        fillOpacity: 0.5,
        strokeOpacity: 0.3
    };
  
    var default_style = new OpenLayers.Style(template, {context: context});
    //var select_style = new OpenLayers.Style(template, {context: context});
    var stylemap = new OpenLayers.StyleMap(
        {
            "default":default_style,
            "select": new OpenLayers.Style(
            {
            fillOpacity: 0.9,
            strokeOpacity: 1,
            cursor: "crosshair",
            }
            )
        }
     );
    return stylemap
    }
   
 /* 
fillColor: "#ee9900",
fillOpacity: 0.4,
hoverFillColor: "white",
hoverFillOpacity: 0.8,
strokeColor: "#ee9900",
strokeOpacity: 1,
strokeWidth: 1,
strokeLinecap: "round",
hoverStrokeColor: "red",
hoverStrokeOpacity: 1,
hoverStrokeWidth: 0.2,
pointRadius: 6,
hoverPointRadius: 1,
hoverPointUnit: "%",
pointerEvents: "visiblePainted",
cursor: "inherit"
    
                for (var n=0; n < feature.geometry.components.length; n++) {
                    if ( feature.geometry.components[n].CLASS_NAME == "OpenLayers.Geometry.Polygon" ) {
                                return "purple"
                                }
                    else if ( feature.geometry.components[n].CLASS_NAME == "OpenLayers.Geometry.Point" ) {
                                return "green"
                                }
                    else if ( feature.geometry.components[n].CLASS_NAME == "OpenLayers.Geometry.LineString" ) {
                                return "yellow"
                                }
                };
   */  
   
function raiseSelectedFeature (){
    if (vectors.selectedFeatures.length >0) {
    var f = vectors.selectedFeatures[0];
    vectors.removeFeatures(f);
    vectors.addFeatures(f);
}}

function lowerSelectedFeature (){
    if (vectors.selectedFeatures.length >0){
    var f = vectors.selectedFeatures[0];
    vectors.removeFeatures(f);
    var remainder = vectors.features
    var remainder_clone = []
    for (var key in remainder) {
    feat = vectors.features[key]
    remainder_clone[key] = feat
    console.log(feat)
    console.log(remainder_clone)
    
    vectors.removeFeatures(feat);  
    };
    vectors.addFeatures(f);
    for (var key in remainder_clone) {
    vectors.addFeatures(remainder_clone[key]);  
    };
    
    }    }

    
function init(geometry){
            //OpenLayers.ImgPath = "/static/openlayers/theme/img/";
                var map_options = {
                    projection: new OpenLayers.Projection("EPSG:4326"),
                    units: "m",
                    //controls = null,
                   // theme : null,
                    //maxExtent: new OpenLayers.Bounds(180, 90, -180, -90),
                    numZoomLevels: 15
                    }
            
            map = new OpenLayers.Map('map', map_options);

            graphic = new OpenLayers.Layer.Image(
                'A Boundary Marker from Bulgaria',
                'http://localhost/cgi-bin/wms/mapnikwms.py?LAYERS=world&FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&BBOX=-128.21790088231415,43.15396915976346,-120.82045815121619,50.55141189086143&WIDTH=256&HEIGHT=256',
                new OpenLayers.Bounds(-128.217,43.153,-120.820,50.551),
                new OpenLayers.Size(256,256),
                options
                );
          //vectors.features[0].atPoint(new OpenLayers.LonLat(39.0234375, 62.578125))
         // vectors = new OpenLayers.Layer.GML("test","http://localhost:8000/geojson/", {
         vectors = new OpenLayers.Layer.GML("test","features/" + geometry + ".json", {
                format: OpenLayers.Format.GeoJSON, 
                styleMap: getGeomStyle(), 
                isBaseLayer: true,
                extractStyles: true,
                projection: new OpenLayers.Projection("EPSG:4326"), 
                'attribution': "<a href='http://www.openlayers.org'>Powered by Openlayers</a>"}
            );
            
            
            map.addLayers([vectors, graphic]);
            //map.zoomToMaxExtent();
            if (!map.getCenter()) map.zoomToMaxExtent();
            //map.getControlsByClass('OpenLayers.Control.PanZoom')[0].destroy()
            map.addControl(new OpenLayers.Control.MousePosition('mousepostion'));
            map.addControl(new OpenLayers.Control.LayerSwitcher());
            map.addControl(new OpenLayers.Control.Scale());
            var panel = new OpenLayers.Control.Panel({'displayClass': 'olControlEditingToolbar'});
            var nav = new OpenLayers.Control.Navigation();
            var l = new OpenLayers.Control.DrawFeature(vectors, OpenLayers.Handler.Path, {'displayClass': 'olControlDrawFeaturePath'});
            var g = new OpenLayers.Control.DrawFeature(vectors, OpenLayers.Handler.Polygon, {'displayClass': 'olControlDrawFeaturePolygon'});
            var p = new OpenLayers.Control.DrawFeature(vectors, OpenLayers.Handler.Point, {'displayClass': 'olControlDrawFeaturePoint'});
            //var mod = new OpenLayers.Control.ModifyFeature(vectors, {'displayClass': 'olControlModifyFeature'});
            panel.addControls([nav,p,g, l]);
            map.addControl(panel);
            map.getControlsByClass('OpenLayers.Control.Navigation')[0].disableZoomWheel()
            
            var options = {
               //hover: true,
               toggle : true,
               toggleKey: "ctrlKey",
               multipleKey: "shiftKey",
               multiple: true,
               clickout: true,
               onSelect: function(feature) { 
                   getWKT(feature); 
               },
               onUnselect: function(feature) { 
                   getWKT(feature); 
               }
             };
             
           
            
            var select = new OpenLayers.Control.SelectFeature(vectors, options);
            map.addControl(select);
            //select.handler.stopDown = false;
            //select.handler.stopUp = false;
            select.activate();
            
            function loadJson (event) {
                features = event.features
                //var max_bounds = getFeaturesExtent(features);
                if (vectors.features.length > 0) {
                    var max_bounds = vectors.getDataExtent()
                    //var max_bounds = getVectorsExtent();
                    //var max_bounds = new OpenLayers.Bounds(-128.217,43.153,-120.820,50.551);
                    map.zoomToExtent(max_bounds);
                    $("olGeomType").innerHTML = getDataTypes(features);
                    map.setOptions({restrictedExtent: max_bounds});
                    getGeomStyle();
                };
                }
    
            vectors.events.on({"featuresadded": loadJson});
            vectors.events.on({"featuremodified": modWKT});
            
            
        }
    


            
            
         

